package com.suke.czx.modules.wx.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.mts.model.v20140618.SubmitJobsRequest;
import com.aliyuncs.mts.model.v20140618.SubmitJobsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.suke.czx.common.utils.JsonResult;
import com.suke.czx.common.utils.Tools;
import com.suke.czx.modules.wx.config.WxMpConfiguration;
import com.suke.czx.modules.wx.config.WxPayProperties;
import com.suke.czx.modules.wx.cons.Constant;
import com.suke.czx.modules.wx.util.AmrToMp3;
import com.suke.czx.modules.wxadmin.entity.DkUserEntity;
import com.suke.czx.modules.wxadmin.entity.DkUserRecordEntity;
import com.suke.czx.modules.wxadmin.service.DkUserRecordService;
import com.suke.czx.modules.wxadmin.service.DkUserService;

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@RestController
@RequestMapping("/wx/record")
public class WxRecordController extends BaseController {

	private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private DkUserService dkUserService;
	@Autowired
	private DkUserRecordService dkUserRecordService;
	@Autowired 
	private WxPayProperties wxPayProperties;

	
	String endpoint = "oss-cn-shenzhen-internal.aliyuncs.com";
	// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录
	// https://ram.console.aliyun.com 创建。
	static String accessKeyId = "DE929rKOa8bzsYY5";
	static String accessKeySecret = "zat5D8YbCPnOzYnTXWipjRGD2n5W4n";

	private static IAcsClient getIAcsClient() {
		DefaultProfile profile = DefaultProfile.getProfile("cn-shenzhen", // 地域ID
				accessKeyId, // 您的AccessKey ID
				accessKeySecret // 您的AccessKey Secret
		);
		return new DefaultAcsClient(profile);
	}

	@RequestMapping("/save")
	public String save(String sid,Integer rid) {
		
//		if(true){
//			return new JsonResult(200, "录制音频上传成功！").toJson();
//		}
//		
		if(null==sid||null==rid){
			return new JsonResult(200, "上传音频失败！").toJson();
		}
		
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}

		DkUserEntity dkUser = dkUserService.queryObject(wxMpUser.getOpenId(),true);
		if (dkUser.getState() == 0) {
			return new JsonResult(23, "用户未订购，请跳转购买链接！").toJson();
		}
		
		Map<String,Object> parms = new HashMap<>();
		parms.put("user_id", wxMpUser.getOpenId());
		parms.put("rid", rid);
		DkUserRecordEntity dre = dkUserRecordService.queryByUserIdAndRid(parms);
		
		
		WxMpService wxMpService = WxMpConfiguration.getMpServices().get(wxPayProperties.getAppId());
		try {
			// 1、更具sid 下载文件上传阿里云oss
			int randomnum = Tools.getRandomNum();
			File file = wxMpService.getMaterialService().mediaDownload(sid);
			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			//2、本地转码服务
			String targetFilePath = "/root/"+randomnum+".mp3";
			boolean flag = AmrToMp3.changeProcess(file.getAbsolutePath(), targetFilePath);
			if(flag){
				File targetFile = new File(targetFilePath);
				ossClient.putObject("story2018", "voice/" + wxMpUser.getOpenId() + "/" + randomnum + ".mp3", targetFile);
				logger.info("============> 本地转码成功！");
				targetFile.delete();
			}else{
				logger.info("============> 本地转码失败，开始云端转码！");
				ossClient.putObject("story2018", "voice/" + wxMpUser.getOpenId() + "/" + randomnum + ".amr", file);
				
				// 2、按需求转换amr格式到mp3

				// Oss region / 输出Bucket所在地域
				String OssLocation = "oss-cn-shenzhen";
				// Oss bucket / 输出Bucket
				String OssBucket = "story2018";
				// Oss Input Object / 输入文件名,路径
				String OssInputObject = "voice/" + wxMpUser.getOpenId() + "/" + randomnum + ".amr";
				// Oss Output Object / 输出文件名,路径
				String OssOutputObject = "voice/" + wxMpUser.getOpenId() + "/" + randomnum + ".mp3";
				// Template Id / 输出模板ID
				String TemplateId = "a9866e9de91e4d53a87f1a05a456a594";
				// Pipeline Id / 管道ID
				String PipelineId = "e10be63aa96843be8c9150c8f14b23b6";
				// 创建API请求并设置参数
				SubmitJobsRequest request = new SubmitJobsRequest();
				// Input / 作业输入，JSON对象
				JSONObject input = new JSONObject();
				input.put("Location", OssLocation);
				input.put("Bucket", OssBucket);
				try {
					input.put("Object", URLEncoder.encode(OssInputObject, "utf-8"));
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException("input URL encode failed");
				}
				request.setInput(input.toJSONString());
				// Output / Outputs由Output列表构成，JSON数组，大小上限为30
				String outputOSSObject;
				try {
					outputOSSObject = URLEncoder.encode(OssOutputObject, "utf-8");
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException("output URL encode failed");
				}
				JSONObject output = new JSONObject();
				output.put("OutputObject", outputOSSObject);
				// Ouput->TemplateId
				output.put("TemplateId", TemplateId);
				JSONArray outputs = new JSONArray();
				outputs.add(output);
				request.setOutputs(outputs.toJSONString());
				request.setOutputBucket(OssBucket);
				request.setOutputLocation(OssLocation);
				// PipelineId
				request.setPipelineId(PipelineId);
				// 发起请求并处理应答或异常
				SubmitJobsResponse response;
				response = getIAcsClient().getAcsResponse(request);
				logger.info("RequestId is:" + response.getRequestId());
				if (response.getJobResultList().get(0).getSuccess()) {
					logger.info("JobId is:" + response.getJobResultList().get(0).getJob().getJobId());
				} else {
					logger.info("SubmitJobs Failed code:" + response.getJobResultList().get(0).getCode() + " message:"
							+ response.getJobResultList().get(0).getMessage());
				}
			}
			// 3、存储对应的文件；
			if(null==dre){
				DkUserRecordEntity userRecord = new DkUserRecordEntity();
				userRecord.setUserId(wxMpUser.getOpenId());
				userRecord.setCreateTime(new Date());
				userRecord.setVoiceName(randomnum + "");
				userRecord.setVoiceUrl(
						"http://img.hbanbao.com/" + "voice/" + wxMpUser.getOpenId() + "/" + randomnum + ".mp3");
				userRecord.setNickname(wxMpUser.getNickname());
				userRecord.setHeadimg(wxMpUser.getHeadImgUrl());
				userRecord.setSid(rid);
				userRecord.setLove(0);
				dkUserRecordService.save(userRecord);
			}else{
				//删除阿里云多余文件
				if(!flag){
					ossClient.deleteObject("story2018", "voice/" + wxMpUser.getOpenId() + "/" + dre.getVoiceName() + ".amr");
				}
				ossClient.deleteObject("story2018", "voice/" + wxMpUser.getOpenId() + "/" + dre.getVoiceName() + ".mp3");
				//更新音频文件
				dre.setVoiceName(randomnum + "");
				dre.setVoiceUrl(
						"http://img.hbanbao.com/" + "voice/" + wxMpUser.getOpenId() + "/" + randomnum + ".mp3");
				dkUserRecordService.update(dre);
			}
			ossClient.shutdown();
			return new JsonResult(200, "录制音频上传成功！").toJson();

		} catch (Exception e) {
			e.printStackTrace();
			return new JsonResult(-1, e.getMessage()).toJson();
		}
	}
	@RequestMapping("/love")
	public String love(Integer id) {
		
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}
		if (null == id) {
			return new JsonResult(-1, "诗词ID不能为空！").toJson();
		}
		
		DkUserRecordEntity dre = dkUserRecordService.queryObject(id);
		if(null!=dre){
			dre.setLove(dre.getLove()+1);
			dkUserRecordService.update(dre);
		}
		
		return new JsonResult(200, "点赞成功！").toJson();
	}
	
	@RequestMapping("/mylist")
	public String mylist() {
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}
		List<DkUserRecordEntity> lsit = dkUserRecordService.queryListByUserId(wxMpUser.getOpenId());
		return new JsonResult(200, "ok", lsit).toJson();
	}
	
	/**
	 * 根据当前阅读页面的id获取对应的用户上传的音频
	 * @param rid
	 * @return
	 */
	@RequestMapping("/rlist")
	public String list(String rid) {
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}
		List<DkUserRecordEntity> list = dkUserRecordService.queryListByRid(rid);
		
		return new JsonResult(200, "ok", list).toJson();
	}
	/**
	 * 获取自己的音频在当前阅读页面上面
	 * @param rid
	 * @return
	 */
	@RequestMapping("/rmine")
	public String rmine(String rid) {
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}
		Map<String,Object> parms = new HashMap<>();
		parms.put("user_id", wxMpUser.getOpenId());
		parms.put("rid", rid);
		DkUserRecordEntity dre = dkUserRecordService.queryByUserIdAndRid(parms);
		return new JsonResult(200, "ok", dre).toJson();
	}
	
	@RequestMapping("/delete")
	public String delete(Integer id) {
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}
	    DkUserRecordEntity userRecord =	dkUserRecordService.queryObject(id);
		//1、删除数据库
		dkUserRecordService.delete(id);
		//2、删除阿里云
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		ossClient.deleteObject("story2018", "voice/" + wxMpUser.getOpenId() + "/" + userRecord.getVoiceName() + ".amr");
		ossClient.deleteObject("story2018", "voice/" + wxMpUser.getOpenId() + "/" + userRecord.getVoiceName() + ".mp3");
		ossClient.shutdown();
		return new JsonResult(200, "ok").toJson();
	}
	
	

}
